//
//  PaparazziAppDelegate.m
//  Paparazzi
//
//  Created by Eric Williams on 10/24/10.
//  Copyright 2010 Eric Williams. All rights reserved.
//

#import "PaparazziAppDelegate.h"
#import "PersonTableViewController.h"
#import "PhotoTableViewController.h"
#import "MapViewController.h"

#import "Person.h"
#import "Photo.h"
#import "Recent.h"

@implementation PaparazziAppDelegate

@synthesize window;


#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

	// Set a short delay for the splash screen
	//[NSThread sleepForTimeInterval: 0.5];
	
	flickrFetcher = [FlickrFetcher sharedInstance];
	
	// Create the database if it doesn't exist yet and fill it
	if(![flickrFetcher databaseExists]) {
		
		// Load the pList Data into Core Data
		[self loadCoreData];
	}
	
	// Load the main UI components (i.e. the Nav view, the TabBar view, and any necessary Tables views)
	[self loadMainUI];
	
    [window makeKeyAndVisible];
    
    return YES;
}

- (void)loadCoreData {
	
	// Load the plist in memory and transfer it into Core Data (BUT ONLY ONE TIME!!!)
	NSString *rootPath = [self applicationDocumentsDirectory];
	NSString *plistPath = [rootPath stringByAppendingPathComponent: @"Startup.plist"];
	NSString *bundlePath = [[NSBundle mainBundle] pathForResource: @"Startup" ofType: @"plist"]; 
	
	// Pull the data from the Bundle object in the Resources directory...
	NSFileManager *defaultFile = [NSFileManager defaultManager];
	BOOL isInstalled = [defaultFile fileExistsAtPath: plistPath];
	
	NSArray *plistData;
	
	if(isInstalled == NO)
	{   
		// CREATE A MANAGED Recent OBJECT ON THE FIRST LOAD	
		Recent *recent = [NSEntityDescription insertNewObjectForEntityForName: @"Recent" inManagedObjectContext: flickrFetcher.managedObjectContext];
		[flickrFetcher.managedObjectContext save: nil];
	 
		plistData = [NSArray arrayWithContentsOfFile :bundlePath];
		
		if(plistData)
		{
			[plistData writeToFile: plistPath atomically:YES];
		}      
	}
	else {
		plistData = [NSArray arrayWithContentsOfFile: plistPath];
	}
}

- (void) loadMainUI {
	// Generate the tab controller
	tabController = [[UITabBarController alloc] init];
	
	// Generate the nav controller for Contacts
	navContactController = [[UINavigationController alloc] init];
	navContactController.navigationBar.tintColor = [UIColor lightGrayColor];
	
	// Generate the nav controller for Recents
	navRecentController = [[UINavigationController alloc] init];
	navRecentController.navigationBar.tintColor = [UIColor lightGrayColor];
	
	// Generate the nav controller for the Map
	navMapController = [[UINavigationController alloc] init];
	navMapController.navigationBar.tintColor = [UIColor lightGrayColor];
	
	// Generate an initial table view for the first nav controller
	PersonTableViewController *personTableViewController = [[PersonTableViewController alloc] initWithStyle: UITableViewStylePlain];
	
	personTableViewController.title = @"All Contacts";
	
	UIBarButtonItem *contactsBack = [[UIBarButtonItem alloc] initWithTitle:@"Contacts" style:UIBarButtonItemStyleBordered target:nil action:nil];
	personTableViewController.navigationItem.backBarButtonItem = contactsBack;
	[contactsBack release];
	
	UITabBarItem *contactsTab = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemContacts tag:0];
	personTableViewController.tabBarItem = contactsTab;	
	[contactsTab release];
	
	[navContactController pushViewController: personTableViewController animated: NO];
	[personTableViewController release];

	
	// Generate an initial view for the second nav controller
	// Create the table to eventually fill with people
	PhotoTableViewController *photoTableViewController = [[PhotoTableViewController alloc] initWithStyle: UITableViewStylePlain];
	
	photoTableViewController.title = @"Recent Photos";
	photoTableViewController.multiUser = YES;
	photoTableViewController.person = nil;
	
	// Link back to the PersonTableViewController
//	personTableViewController.contactDelegate = photoTableViewController;
	
	UIBarButtonItem *recentBack = [[UIBarButtonItem alloc] initWithTitle:@"Recent" style:UIBarButtonItemStyleBordered target:nil action:nil];
	photoTableViewController.navigationItem.backBarButtonItem = recentBack;
	[recentBack release];
	
	UITabBarItem *recentTab = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemRecents tag:0];
	photoTableViewController.tabBarItem = recentTab;
	[recentTab release];
	
	[navRecentController pushViewController: photoTableViewController animated: NO];
	[photoTableViewController release];	
	
	// Generate an initial map for the Map Tab
	MapViewController *mapViewController = [[MapViewController alloc] init];

	mapViewController.title = @"Photo Locations";
	
	UIBarButtonItem *mapBack = [[UIBarButtonItem alloc] initWithTitle:@"Map" style:UIBarButtonItemStyleBordered target:nil action:nil];
	mapViewController.navigationItem.backBarButtonItem = mapBack;
	[mapBack release];
	
	// TODO
	UITabBarItem *mapTab = [[UITabBarItem alloc] initWithTitle: @"Map" image: [UIImage imageNamed: @"globe.png"] tag:0];
	mapViewController.tabBarItem = mapTab;	
	[mapTab release];
	
	[navMapController pushViewController: mapViewController animated: NO];
	[mapViewController release];
	
	// Add the array of nav controllers on top of the tab controller
	tabController.viewControllers = [NSArray arrayWithObjects: navContactController, navRecentController, navMapController, nil];
	
	// Add the tab controller on top of the main window
	[window addSubview: tabController.view];	
}

- (void)applicationWillResignActive:(UIApplication *)application {
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
//    [self saveContext];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of the transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
	
	// Set a short delay for the splash screen
	//[NSThread sleepForTimeInterval: 1.0];
}


/*
 applicationWillTerminate: saves changes in the application's managed object context before the application terminates.
 */
- (void)applicationWillTerminate:(UIApplication *)application {
//    [self saveContext];
}


#pragma mark -
#pragma mark Application's Documents directory


// Returns the path to the application's Documents directory.

- (NSString *)applicationDocumentsDirectory {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}


#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    
    // Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
 
}


- (void)dealloc {
    
	[tabController release];
	[navRecentController release];
	[navContactController release];
	[navMapController release];
	
    //[managedObjectContext_ release];
    //[managedObjectModel_ release];
    //[persistentStoreCoordinator_ release];
    
    [window release];
    [super dealloc];
}


@synthesize tabController;
@synthesize navContactController;
@synthesize navRecentController;
@synthesize navMapController;
@synthesize flickrFetcher;
@end

